package com.sky.server;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

@Slf4j
public class IOServer {
    public static void main(String[] args) {
        byte[] buffer = new byte[1024];

        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            log.info("服务器已启动并监听8080端口");
            for (;;) {
                log.info("服务器正在等待连接");
                Socket accept = serverSocket.accept();
                log.info("服务器已接收到连接请求");
                new Thread(() -> {
                    log.info("服务器正在等待数据");
                    try {
                        accept.getInputStream().read(buffer);
                        log.info("服务器已经接收到数据");
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    String s = new String(buffer, StandardCharsets.UTF_8);
                    log.info("服务器接收到的数据为：{}", s);
                }).start();
            }
        } catch (IOException e) {
            log.info("异常", e);
            throw new RuntimeException(e);
        }
    }
}

class Consumer {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1", 8080);
            String message = null;
            Scanner scanner = new Scanner(System.in);
            message = scanner.next();
            socket.getOutputStream().write(message.getBytes(StandardCharsets.UTF_8));
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
